package jdbc.mysql;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

public class MysqlJdbcTest {

    //数据库连接对象
    private static Connection conn = null;

    private static String driver = "net.sf.log4jdbc.DriverSpy"; //驱动
    //private static String driver = "com.mysql.jdbc.Driver"; //驱动

    //private static String url = "jdbc:mysql://localhost:3306/mysql?createDatabaseIfNotExist=true&useUnicode=true"; //连接字符串
    private static String url = "jdbc:log4jdbc:mysql://localhost:3306/mysql?createDatabaseIfNotExist=true&useUnicode=true"; //连接字符串
    private static String username = "root"; //用户名

    private static String password = "root"; //密码


    // 获得连接对象
    private static synchronized Connection getConn() {
        if (conn == null) {
            try {
                Class.forName(driver);
                Properties props = new Properties();
                //此行根据官方文档格式写，未作验证
                props.put("user", username);
                props.put("password", password);
                conn = DriverManager.getConnection(url, props);
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return conn;
    }

    //执行查询语句
    public void query(String sql, boolean isSelect) throws SQLException {
        PreparedStatement pstmt;

        try {
            pstmt = getConn().prepareStatement(sql);
            //建立一个结果集，用来保存查询出来的结果
            ResultSet rs = pstmt.executeQuery();
            while (rs.next()) {
                String name = rs.getString(1);
                System.out.println(name);
            }
            rs.close();
            pstmt.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public void query(String sql) throws SQLException {
        PreparedStatement pstmt;
        pstmt = getConn().prepareStatement(sql);
        pstmt.execute();
        pstmt.close();
    }


    //关闭连接
    public void close() {
        try {
            getConn().close();

        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
